var scene, camera, renderer, group, role, mixer, material, action;
var actionState = "";
var roleAnimations = [];
var timer = null;
var ASSETSURL = "../assets/05/"; // 资源主目录路径
var clock = new THREE.Clock();
var w = window.innerWidth,
  h = window.innerHeight;
var isOpen = false;

(function () {
  initVariable();
  createStage();
  addLight();
  loadModel();

  loop();
  setTimeout(() => {
    changeChat(0, "right").show(true);
    addUIEvent();
  }, 500);
  // new THREE.OrbitControls(camera, renderer.domElement);
})();

function changeChat(index, type) {
  return {
    show: function (isbuy) {
      $("#chat" + index).show();
      new TweenMax.fromTo(
        "#chat" + index,
        0.5,
        {
          x: type == "left" ? -w : w,
          opacity: 0,
        },
        {
          x: 0,
          opacity: 1,
          onComplete: function () {
            if (!isbuy) return;
            $(".btns-box").show();
            new TweenMax.fromTo(
              ".key-btns",
              0.5,
              {
                y: 100,
                opacity: 0,
              },
              {
                y: 0,
                opacity: 1,
              }
            );
          },
        }
      );
    },
  };
}

function addUIEvent() {
  var btns = document.querySelectorAll(".key-btn");
  btns.forEach(function (btn) {
    btn.addEventListener(
      "click",
      function (e) {
        var type = e.target.dataset.type;
        console.log(type);
        if (isOpen) return;
        isOpen = true;
        var data = [
          {
            money: 50,
            name: "铜钥匙",
          },
          {
            money: 200,
            name: "银钥匙",
          },
          {
            money: 500,
            name: "金钥匙",
          },
        ];
        $("#money").html(data[type].money);
        $("#key").html(data[type].name);
        new TweenMax.to(".key-btns", {
          duration: 0.5,
          y: 100,
          opacity: 0,
        });
        changeChat(1, "left").show();
        setTimeout(function () {
          changeChat(2, "right").show();
        }, 500);
        setTimeout(() => {
          $(".chat").hide();
          runAnimation();
        }, 2200);
      },
      false
    );
  });
}

function runAnimation() {
  initRole();
  var timer = new gsap.timeline({
    onUpdate: function () {
      //update();
    },
    defaults: { duration: 0 },
  });
  timer.to(
    role.position,
    {
      duration: 1,
      y: 0,
      ease: Bounce.easeOut,
    },
    0
  );
  // timer.to(
  //   ".key-btns",
  //   {
  //     duration: 0.5,
  //     y: 100,
  //     opacity: 0,
  //   },
  //   0.2
  // );
  timer.to(
    camera.position,
    {
      duration: 1.2,
      y: 24,
      z: 20,
      onComplete: function () {
        actionAnimation(0);
      },
    },
    1
  );
}
// 创建地面
function createStage() {
  var plane_map = new THREE.TextureLoader().load(
    ASSETSURL + "imgs/bathroom.jpg"
  );
  var plane_normal_map = new THREE.TextureLoader().load(
    ASSETSURL + "imgs/bathroom-normal.jpg"
  );
  var wall_map = new THREE.TextureLoader().load(ASSETSURL + "imgs/stone.jpg");
  var wall_bump_map = new THREE.TextureLoader().load(
    ASSETSURL + "imgs/stone-bump.jpg"
  );

  plane_map.wrapS =
    plane_normal_map.wrapS =
    wall_map.wrapS =
    wall_bump_map.wrapS =
      THREE.RepeatWrapping;
  plane_map.wrapT =
    plane_normal_map.wrapT =
    wall_map.wrapT =
    wall_bump_map.wrapT =
      THREE.RepeatWrapping;

  plane_map.repeat.set(3, 3);
  plane_normal_map.repeat.set(3, 3);

  wall_bump_map.repeat.set(3, 3);
  wall_map.repeat.set(3, 3);

  // MeshPhysicalMaterial
  // MeshBasicMaterial
  // MeshDepthMaterial
  // MeshLambertMaterial
  // MeshMatcapMaterial

  var mesh = new THREE.MeshPhysicalMaterial({
    map: plane_map,
    normalMap: plane_normal_map,
    side: THREE.DoubleSide,
  });

  var wall_mesh = new THREE.MeshPhysicalMaterial({
    map: wall_map,
    bumpMap: wall_bump_map,
    side: THREE.DoubleSide,
  });

  console.log(wall_mesh);
  // mesh.reflectivity = 0;
  // mesh.clearCoatRoughness = 0.3;

  mesh.roughness = 1;
  mesh.metalness = 1;

  wall_mesh.roughness = 1.04;
  wall_mesh.metalness = 1.04;
  // mesh.reflectivity = 0;
  // mesh.emissiveIntensity = 0.1;
  // mesh.lightMapIntensity = 0.1;
  // mesh.skinning = true;
  // mesh.aoMapIntensity = 0;

  var plane = new THREE.Mesh(new THREE.BoxBufferGeometry(60, 60, 1), mesh);
  plane.receiveShadow = true;
  plane.castShadow = true;
  plane.position.set(0, -0.5, 0);
  plane.rotation.x = 0.5 * Math.PI;
  scene.add(plane);

  var wall = new THREE.Mesh(new THREE.BoxBufferGeometry(60, 40, 1), wall_mesh);
  wall.position.set(0, 20, -30);
  wall.rotation.x = 0;

  scene.add(wall);
}

function update() {
  var delta = clock.getDelta();
  if (mixer) mixer.update(delta);
  renderer.render(scene, camera);
  camera.lookAt(scene.position);
}

function addLight() {
  var ambientLight = new THREE.AmbientLight(
    new THREE.Color("rgb(185,185,185)")
  );
  ambientLight.intensity = 3;
  scene.add(ambientLight);

  var frontDirLight = new THREE.DirectionalLight(
    new THREE.Color("rgb(195,195,195)")
  );

  frontDirLight.position.x = 0;
  frontDirLight.position.y = 300;
  frontDirLight.position.z = 50;
  frontDirLight.intensity = 4;
  // frontDirLight.castShadow = true;
  // frontDirLight.receiveShadow = true;
  scene.add(frontDirLight);

  var frontDirLight2 = new THREE.DirectionalLight(
    new THREE.Color("rgb(255,255,255)")
  );

  frontDirLight2.position.x = 0;
  frontDirLight2.position.y = 30;
  frontDirLight2.position.z = 80;
  frontDirLight2.intensity = 2;
  frontDirLight2.castShadow = true;
  frontDirLight2.receiveShadow = true;
  scene.add(frontDirLight2);

  // var helper = new THREE.DirectionalLightHelper(frontDirLight, 1);
  // scene.add(helper);
  // var helper2 = new THREE.DirectionalLightHelper(frontDirLight2, 1);
  // scene.add(helper2);
}

function initVariable() {
  // 创建摄像机
  camera = new THREE.PerspectiveCamera(
    50,
    document.body.clientWidth / document.body.clientHeight,
    0.2,
    1000
  );
  camera.position.z = 36;
  camera.position.y = 20;

  // 初始化场景
  scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2(0x05050c, .015);

  group = new THREE.Group();
  scene.add(group);

  // 初始化renderer
  renderer = new THREE.WebGLRenderer({
    antialias: true,
    alpha: true,
  });
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.getElementById("container").appendChild(renderer.domElement);

  // 监听窗口尺寸改变
  window.addEventListener("resize", onWindowResize, false);
}

function onWindowResize() {
  // 窗口尺寸改变
  try {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  } catch (error) {
    console.log(error);
  }
}

function loadModel(callback) {
  var loader = new THREE.GLTFLoader();
  loader.load(ASSETSURL + "model/scene.gltf", function (gltf) {
    role = gltf.scene;
    material = [
      role.children[0].children[0].children[0].children[0].children[0]
        .children[0].children[0].children[0].material,
    ];
    console.log(material[0]);
    material[0].roughness = 1;
    material[0].metalness = 1;
    material[0].reflectivity = 0;
    material[0].color = material[0].emissive = new THREE.Color(
      "rgb(195,195,195)"
    );

    role.children[0].children[0].children[0].children[0].children[0].children[1].children.forEach(
      function (item) {
        // console.log(item);
        if (item.children[0].material) {
          material.push(item.children[0].material);
        }
      }
    );
    // console.log(
    //   role.children[0].children[0].children[0].children[0].children[0]
    // );
    // console.log(material);
    roleAnimations = gltf.animations;
    mixer = new THREE.AnimationMixer(role);
    mixer.addEventListener("finished", function (e) {
      console.log(e);
      if (isOpen) showSuccessUI();
    });
    initRole();
    group.add(role);
    callback && callback();
  });
}

function initRole() {
  role.scale.set(0.1, 0.1, 0.1);
  role.position.set(0, 20, 0);
  material.forEach(function (mater) {
    mater.opacity = 1;
    mater.transparent = true;
  });
  try {
    action.stop();
    action.time = 0;
    action.loop = THREE.LoopOnce;
    action.clampWhenFinished = true;
  } catch (error) {}
}

function actionAnimation(index) {
  actionState = roleAnimations[index].name;
  action = mixer.clipAction(roleAnimations[index]);
  action.time = 0;
  action.loop = THREE.LoopOnce;
  action.clampWhenFinished = true;
  action.setDuration(2);
  action.stopWarping();
  action.play();
}

function toAngle(n) {
  return (Math.PI / 180) * n;
}

function loop() {
  requestAnimationFrame(loop);
  update();
}

function hideSuccessUI() {
  isOpen = false;
  var timer = new gsap.timeline({
    defaults: { duration: 0 },
  });
  timer.to(
    ".success-box",
    0.8,
    {
      scale: 0,
      opacity: 0,
      ease: Cubic.easeOut,
      onComplete: function () {
        $(".mask").hide();
        $(".success-box").hide();
        mixer.stopAllAction();
      },
    },
    0
  );

  timer.to(
    role.position,
    {
      duration: 0.8,
      y: 20,
    },
    1
  );
  timer.to(
    material,
    {
      duration: .6,
      opacity: 0,
      ease: Back.easeOut.config(1.2),
    },
    1
  );
  // timer.to(
  //   ".key-btns",
  //   {
  //     duration: 0.5,
  //     y: 0,
  //     opacity: 1,
  //   },
  //   1
  // );
  timer.to(
    camera.position,
    {
      duration: 1.2,
      y: 20,
      z: 36,
      onComplete: function () {
        $("#chat0>p").html("这里还有好多，还要来点么?");
        changeChat(0, "right").show(true);
      },
    },
    0.7
  );
}

function showSuccessUI() {
  $(".mask").show();
  $(".success-box").show();
  $(".close").off("click").on("click", hideSuccessUI);
  var timer = new gsap.timeline({
    defaults: { duration: 0 },
  });
  timer.fromTo(
    ".success-box",
    0.8,
    {
      scale: 0,
      opacity: 0.5,
    },
    {
      scale: 1,
      opacity: 1,
      ease: Cubic.easeOut,
    },
    0
  );

  timer.staggerFromTo(
    ".item",
    0.8,
    {
      scale: 0,
      opacity: 0.5,
    },
    {
      scale: 1,
      opacity: 1,
      ease: Bounce.easeOut,
    },
    0.25
  );
}
